package com.ai.dmc.utils.export.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.Validate;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import com.ai.dmc.utils.entity.exportformExhibition.TblCell;
import com.ai.dmc.utils.export.ExportSvcRpt;
import com.ai.dmc.utils.zip.ZipUtil;


/**
 * 
 * @see
 * @author tod
 * @date 2015-2-11 上午9:57:14
 * @version
 * @desc TODO
 */
public class XlsExportSvcRptImpl implements ExportSvcRpt {

	private Workbook workbook;// 工作�?
	private Map<Integer, Sheet> sheetMap; // sheet�?
	private Map<Integer, Integer> rowIdxMap; // sheet也对应的当前操作�?
	private CellStyle style; // excel cell 表头单元格样�?
	private CellStyle dataStyle; // excel 数据单元格样�?
	private String title;

	private File file;
	private String filePath;

	public XlsExportSvcRptImpl(String title, String path) {
		
		filePath = path.replace("\\\\", "\\").replace("\\", "/");
		int index = filePath.lastIndexOf("/");
		String fileDir = filePath.substring(0,index);
		String form = filePath.substring(filePath.lastIndexOf("."));
		Validate.isTrue(".xls".equalsIgnoreCase(form),"输入的文件路径后缀必须为.xls");
		File dirFile = new File(fileDir);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
		File file = new File(path);
		try {
			if(!file.exists()){
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("xls创建文件失败");
		}
		this.title = title;
		this.file = file;
		initworkBook();
	}

	private void initworkBook() {
		workbook = new HSSFWorkbook();
		// 表头单元格样�?
		style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		Font font = workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setFont(font);
		// 数据单元格样�?
		dataStyle = workbook.createCellStyle();
		dataStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		dataStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		Font dataFont = workbook.createFont();
		dataFont.setColor(HSSFColor.BLACK.index);
		dataFont.setFontHeightInPoints((short) 10);
		dataFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样�?
		dataStyle.setFont(dataFont);

		sheetMap = new HashMap<Integer, Sheet>();
		rowIdxMap = new HashMap<Integer, Integer>();
	}

	/**
	 * 获取sheet对象进行读写操作
	 * 
	 * @param sheetIndex
	 * @return
	 */
	private Sheet getSheet(Integer sheetIndex) {
		Sheet sheet = sheetMap.get(sheetIndex);
		if (sheet == null) {
			sheet = workbook.createSheet(title + "#" + sheetIndex);
			sheet.setDefaultColumnWidth(15);
			sheetMap.put(sheetIndex, sheet);
			rowIdxMap.put(sheetIndex, 0);
		}
		return sheet;
	}

	/**
	 * 暂时不用多线程处�?--后期如有必要 添加
	 */
	public void writeData(List<Object[]> dataSet, Integer sheetIndex) {
		for (int i = 0; i < dataSet.size(); i++) {
			writeData(dataSet.get(i), sheetIndex);
		}
	}

	public void writeData(Object[] objs, Integer sheetIndex) {
		Sheet sheet = getSheet(sheetIndex);
		Integer rowindex = rowIdxMap.get(sheetIndex);
		Row row = sheet.createRow(rowindex);
		for (int i = 0; i < objs.length; i++) {
			Cell cell = row.createCell(i);
			cell.setCellStyle(dataStyle);
			String str = String.valueOf(objs[i]);
			cell.setCellValue(str);
		}
		rowIdxMap.put(sheetIndex, rowindex + 1);
	}

	public void writeTblHead(List<TblCell>[] heads, Integer sheetIndex) {
		// 创建sheet
		Sheet sheet = getSheet(sheetIndex);
		// 创建表头�?
		List<Row> rows = new ArrayList<Row>();
		for (int i = 0; i < heads.length; i++) {
			rows.add(sheet.createRow(i));
		}
		// 创建单元格并进行合合并同类项
		for (int i = 0; i < heads.length; i++) {
			List<TblCell> list = heads[i];
			int colindex = 0;
			for (int j = 0; j < list.size(); j++) {
				Row rowi = rows.get(i);
				Cell cl = rowi.getCell(colindex);
				while (cl != null) {
					cl = rowi.getCell(++colindex);
				}
				TblCell tblCell = list.get(j);
				int colSpan = tblCell.getColspan();
				int rowSpan = tblCell.getRowspan();
				for (int x = 0; x < colSpan; x++) {
					for (int y = 0; y < rowSpan; y++) {
						int cellx = colindex + x;
						int celly = i + y;
						Row row = rows.get(celly);
						Cell cell = row.createCell(cellx);
						cell.setCellStyle(style);
						cell.setCellValue((String)tblCell.getAlias());
					}
				}
				// 合并单元�?
				sheet.addMergedRegion(new CellRangeAddress(i, i + rowSpan - 1, colindex, colindex + colSpan - 1));
			}
			// 设置sheet�?�?索引
			rowIdxMap.put(sheetIndex, heads.length);
		}
	}

	public void writeFile(boolean needZip,String waterMarkName) {
		FileOutputStream fileout = null;
		try {
			fileout = new FileOutputStream(file);
			workbook.write(fileout);
		} catch (Exception e) {
			throw new RuntimeException("xls写入错误");
		} finally {
			if (fileout != null) {
				try {
					fileout.close();
				} catch (IOException e) {
					throw new RuntimeException("xls写入错误");
				}
			}
		}
		//压缩
		if(needZip){
			String zipPath = filePath.substring(0,filePath.lastIndexOf(".")) +".zip";
			ZipUtil.compress(filePath, zipPath);
		}
	}

//	@SuppressWarnings("unchecked")
//	public static void main(String[] args) {
//		@SuppressWarnings("unchecked")
//		List<TblCell>[] heads = new List[2];
//		List<TblCell> list1 = new ArrayList<TblCell>();
//		List<TblCell> list2 = new ArrayList<TblCell>();
//
//		list1.add(new TblCell("21", "维度1", 1, 2));
//		list1.add(new TblCell("12", "父指�?, 2, 1));
//		list2.add(new TblCell("11", "指标1", 1, 1));
//		list2.add(new TblCell("11", "指标2", 1, 1));
//		heads[0] = list1;
//		heads[1] = list2;
//
//		File file1 = new File("D:\\123321.xls");
//		ExportSvc exportSvc = new XlsExportSvcImpl("测试", file1);
//		exportSvc.writeTblHead(heads, 1);
//		Object[] objs = new Object[3];
//		objs[0] = "合肥";
//		objs[1] = 0.01;
//		objs[2] = 100;
//		Object[] obj1 = new Object[3];
//		obj1[0] = "合肥";
//		obj1[1] = 0.01;
//		obj1[2] = 100;
//		@SuppressWarnings("rawtypes")
//		List list = new ArrayList();
//		list.add(objs);
//		list.add(obj1);
//		exportSvc.writeData(list, 1);
//		exportSvc.writeFile();
//
//	}
}
